package com.leetcode.leetcode3;

/**
 * 反转链表
 *
 * @author luhd
 * @date 2023-08-17
 */
public class Practice206 {
    /**
     * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
     *
     * 输入：head = [1,2,3,4,5]
     * 输出：[5,4,3,2,1]
     */

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        ListNode listNode5 = new ListNode(5);
        head.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        System.out.println(reverseList(head));
    }

    public static ListNode reverseList(ListNode head) {
        /*ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;*/
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}